hfrApp.registerCtrl("AddTopicBlogController", function ($scope, $http, $log, $timeout, $window, $rootScope, HfrConfig, HfrStorage, HfrInit) {
	//Init message alert
	HfrInit.message();
	
	//Display meta header
	HfrConfig.displayMeta("addTopicBlog");
	
	$scope.processing = false;
	
	$scope.selectTopics = [];
	
	if ($rootScope.siteurl === undefined) {
		//$rootScope.siteurl = "http://localhost/wordpress/";
		if (HfrStorage.get("siteUrl") !== null) {
			$rootScope.siteurl = HfrStorage.get("siteUrl");
		} else {
			$window.location.href= "#/add-new-site-wordpress";
		}
	}
	
	//Get all topic
	$http.get(HfrConfig.ApiServiceUrl.topicsUrlApi)
		.success(function (data) {
			$scope.topics = data.response.topics;
			console.log($scope.topics);
		})
		.error(function (data) {
			$scope.topics = {};
		});
	
	
	$scope.add_topic = function (topicForm) {
		$scope.data = {
			blogTopics:[]
		};
		
		angular.forEach($scope.selectTopics, function(value, key) {
			$scope.data.blogTopics.push({
				topicId: value,
				blogId: $rootScope.siteurl,
			});
		});
		
		if ($scope.sizeOf($scope.data.blogTopics) > 0) {
			$scope.processing = true;
			var blogTopicsUrl = HfrConfig.ApiServiceUrl.blogTopicsUrlApi;
			
			$http.post(blogTopicsUrl, $scope.data)
				.success(function (data) {
					//Set delay to display loadding
					$timeout(function(){
						$scope.success = true;
						$scope.processing = false;
						$window.location.href= "#summary";
					}, 3000);
				}).
			    error(function(data) {
			    	$scope.error = false;
			    	$rootScope.message.error = true;
					$rootScope.message.text = "Can't connect to server";
			    });
		} else {
			$rootScope.message.error = true;
			$rootScope.message.text = "Please select a topic.";
		}
		
	};
	
	$scope.select_topic = function (event) {
		if (event.which == 13) {
			var topicId = $scope.topicId;
			var idx = $scope.selectTopics.indexOf(topicId);
			if (idx <= -1 && $scope.topics.hasOwnProperty(topicId)) {
				$scope.selectTopics.push(topicId);
			}
			
			$scope.topicId = "";
		}
	};
	
	$scope.remove_topic = function(topicId) {
		var idx = $scope.selectTopics.indexOf(topicId);
		if (idx > -1) {
			$scope.selectTopics.splice(idx, 1);
		}
	};
	
	//Count size
	$scope.sizeOf = function(obj) {
	    return Object.keys(obj).length;
	};
});